<?php

namespace App\Http\Middleware;

use App\Models\Permission;
use App\Models\SystemLog;
use Closure;

class SystemLogMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $routName = \Route::currentRouteName();

        $permission = Permission::where('name',$routName)->where('type','>',0)->first();

        if(!$permission) {
            return $next($request);
        }
        $user =  $request->user();
        $ip = $request->ip();

        $response = $next($request);

        if(!$user) {
            $user =  \Auth::guard('web')->user();
        }

        //找不到用户不写日志
        if(!$user){
            return $response;
        }

        if(in_array($permission->type,[248,249,258,259,260])){
            //写日志；
            $log = new SystemLog();
            $log->fill(
                [
                    'ip' => $ip,
                    'name' => $user->name,
                    'true_name' => $user->true_name,
                    'type' => $permission->type,
                    'user_id' => $user->id
                ]
            );

            $log->status = $response->getStatusCode() == 200 ? 1 : 0;
            $log->content = $permission->remarks;
            $log->save();
        }
        return $response;

    }
}
